package com.jk.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jk.constant.AliPayConstant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/Alipay")
public class AliPayController {

    /**
     * @param body
     * @author 段卓帆
     * @date 2021/7/1 19:33
     * @return 支付接口
     */
    @RequestMapping("/aliPay/{ordernumber}/{totalprice}/{areaname}")
    public @ResponseBody String aliPay(@PathVariable String ordernumber,
                         @PathVariable String totalprice,
                         @PathVariable String areaname
                         ) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstant.gatewayUrl,
                AliPayConstant.app_id,
                AliPayConstant.merchant_private_key,
                "json",
                AliPayConstant.charset,
                AliPayConstant.alipay_public_key,
                AliPayConstant.sign_type);
        // page
        AlipayTradePagePayRequest alipayPageRequest = new AlipayTradePagePayRequest();
        alipayPageRequest.setReturnUrl(AliPayConstant.return_url);
        alipayPageRequest.setNotifyUrl(AliPayConstant.notify_url);


        //拼接参数
        alipayPageRequest.setBizContent("{\"out_trade_no\":\"" + ordernumber + "\","
                + "\"total_amount\":\"" + totalprice + "\","
                + "\"subject\":\"" + areaname + "\","
                + "\"body\":\"" + "便捷支付" + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        return alipayClient.pageExecute(alipayPageRequest).getBody();
    }




    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public @ResponseBody String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConstant.alipay_public_key, AliPayConstant.charset, AliPayConstant.sign_type); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);
  /*          //支付成功，修复支付状态
            Integer pp_id=116;
            PeripheryOrder order = new PeripheryOrder();
            order.setPp_id(pp_id);
            Map map = peripheryService.changeStatus(order);*/
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }




}
